import { createRouter, createWebHistory } from 'vue-router'
import localCache from '@/utils/cache'
import { firstMenu } from '@/utils/map-menu'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/main',
    },
    {
      path: '/login',
      component: () => import('@/views/login/LoginView.vue'),
    },
    {
      path: '/register',
      component: () => import('@/views/register/RegisterView.vue'),
    },

    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/MainView.vue'),
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('@/views/not-found/NotFoundView.vue'),
    },
    {
      path: '/main/test',
      component: () => import('@/views/main/TestView.vue'),
    },
  ],
})

//导航守卫
//  to: Route: 即将要进入的目标 路由对象
//  from: Route: 当前导航正要离开的路由
//  返回值：决定导航的路径，返回 false 或者返回 Promise 时，代表取消导航。
router.beforeEach((to) => {
  const token = localCache.getCache('token')
  //只有登录了才能进入main页面
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }

  if (to.path === '/main') {
    console.log('firstMenu' + firstMenu?.path)
    return firstMenu?.path
  }
})

export default router
